package cn.fengLone.pay.util.wechat;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;




import cn.fengLone.pay.entity.PayInfo;
import cn.fengLone.pay.entity.WeiXinFull;
import cn.fengLone.pay.util.SimpleUtil;
import cn.fengLone.pay.util.wechat.config.MyConfig;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConstants.SignType;
import com.github.wxpay.sdk.WXPayUtil;

public class WeiXinPayUtil {
	
	private static MyConfig config = null;
	/**
     * 微信APP支付
	 * https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1
     * @param weiXinFull 站点证书信息。
     * @param payInfo 订单信息
     * @return
     */
	public static Map<String,String> appPay(WeiXinFull  weiXinFull,PayInfo payInfo){
		Map<String,String> resultMap = new HashMap<String, String>();
    	Map<String, String> map = payOrder(weiXinFull, payInfo); 
    	
    	String payOrderResult = map.get("return_code");
    	if(payOrderResult.trim().equalsIgnoreCase("SUCCESS")){
        	//APP支付
        	//获取到prepay_id后将参数再次签名传输给APP发起支付。以下是调起微信支付的
//        	String prepay_id = map.get("prepay_id");
        	
        	Map<String, String>  newMap = new HashMap<String, String>();
        	String timestamp = "";
        	try {
        		SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");

                java.util.Date date= new Date(); 

                java.util.Date mydate= myFormatter.parse("1970-01-01");

                long  day=(date.getTime()-mydate.getTime());
                
                day = day/1000;
                timestamp = day+"";
                System.out.println("timestamp：\t"+timestamp);
			} catch (Exception e) {
				// TODO: handle exception
			}
        	
        	//保存订单信息
        	//统一下单接口返回正常的prepay_id，再按签名规范重新生成签名后，将数据传输给APP。
        	//参与签名的字段名为appid，partnerid，prepayid，noncestr，timestamp，package。注意：package的值格式为Sign=WXPay 
        	newMap.put("prepayid",  map.get("prepay_id")); //预支付交易会话ID
        	newMap.put("appid", map.get("appid"));   //应用ID
        	newMap.put("partnerid",  map.get("mch_id"));  //商户号
        	newMap.put("package", "Sign=WXPay");  //扩展字段
        	newMap.put("noncestr",  map.get("nonce_str"));  //随机字符串
        	newMap.put("timestamp",  timestamp);  //时间戳
//        	newMap.put("sign",  map.get("sign"));  //签名
        	
        	String signValue = "";
        	try {
        		//app支付所需所有的参数
        		//https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=8_1#
        		signValue  = WXPayUtil.generateSignature(newMap, weiXinFull.getMchKey());
        		//签名完成，返回app
        		System.out.println(signValue);
        		resultMap.put("return_code", "1");
        		resultMap.put("signValue", signValue);
        		resultMap.put("sign",  map.get("sign"));
        		
        		//resultMap增加未加密前的参数值
        		resultMap.putAll(newMap);
        	} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				resultMap.put("return_code", "0");
        		resultMap.put("return_msg", "平台出现问题，请联系平台开发人员.");
			}
    	}else{
    		//返回给用户错误信息 
    		String msg = map.get("return_msg");
    		System.out.println(msg);
    		resultMap.put("return_code", "0");
			resultMap.put("return_msg", msg);
    	}
		return resultMap;
	}
	
	
	
    /**
     * 统一订单业务
	 * https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1
     * @param weiXinFull 站点证书信息。
     * @param payInfo 订单信息
     * @return
     */
	public static Map<String, String> payOrder(WeiXinFull  weiXinFull,PayInfo payInfo){
    	Map<String, String> resp = new HashMap<String, String>();
    	//String certPath,String app_id,String mchID,String app_key
    	if(config ==null){
    		try {
    			config = new MyConfig(weiXinFull.getAppID(),weiXinFull.getMchID(),weiXinFull.getMchKey());
    		} catch (Exception e1) {
    			// TODO Auto-generated catch block
    			e1.printStackTrace();
    			resp.put("result_code", "FAIL");
    			resp.put("return_msg", "初始化微信支付参数失败!");
    			return resp;
    		} 
    	}
    	  			
        WXPay wxpay = new WXPay(config,SignType.MD5,true);  //上线环境 false,测试环境改为true
        
        Map<String, String> data = new HashMap<String, String>();
        data.put("body", payInfo.getSubject()); //商品简单描述，该字段请按照规范传递，具体请见参数规定
        data.put("out_trade_no", payInfo.getTradeNum());//订单号"2016090910595900000012"
        data.put("device_info", "");//自定义参数，可以为终端设备号(门店号或收银设备ID)，PC网页或公众号内支付可以传"WEB"
        data.put("fee_type", "CNY");//	符合ISO 4217标准的三位字母代码，默认人民币：CNY
        data.put("total_fee", payInfo.getTotal_fee());//订单总金额，单位为分
        data.put("spbill_create_ip", payInfo.getSpbill_create_ip());//APP和网页支付提交用户端ip，Native支付填调用微信支付API的机器IP。
        data.put("notify_url", SimpleUtil.payMap.get("weChatNotiryUrl"));//异步接收微信支付结果通知的回调地址，通知url必须为外网可访问的url，不能携带参数。
//        data.put("notify_url", "http://18253594233.xicp.net:18931/wechatPayNotify/payNotify");//异步接收微信支付结果通知的回调地址，通知url必须为外网可访问的url，不能携带参数。
        
        data.put("trade_type", payInfo.getPayType());  // 此处指定为扫码支付
        data.put("product_id", payInfo.getTradeId()); //trade_type=NATIVE时（即扫码支付），此参数必传。此参数为二维码中包含的商品ID，商户自行定义。
        System.out.println("封装的微信支付订单信息为:\n"+data);
        
        try {
        	//{result_code=SUCCESS, sign=5B4ED76C43FB5EE6F40DE309A4927CDD, mch_id=1482304262, err_code=SUCCESS, return_msg=OK, err_code_des=ok, prepay_id=wx20171221203259953346, appid=wxf3040da2863c4b13, code_url=weixin://wxpay/s/An4baqw, return_code=SUCCESS, nonce_str=2c2de5fa1ecb4dde90679fd813c5375b, device_info=, trade_type=NATIVE}
        	resp = wxpay.unifiedOrder(data);
//            System.out.println(resp);
        } catch (Exception e) {
            e.printStackTrace();
            resp.put("result_code", "FAIL");
			resp.put("return_msg", e.getMessage());
        }
        return resp;
    }
	
	public static Map<String, String> queryOrder(WeiXinFull weiXinFull ,String orderNum){
		Map<String, String> resp = new HashMap<String, String>();
		
    	//String certPath,String app_id,String mchID,String app_key
    	if(config ==null){
    		try {
    			config = new MyConfig(weiXinFull.getAppID(),weiXinFull.getMchID(),weiXinFull.getMchKey());
    		} catch (Exception e1) {
    			// TODO Auto-generated catch block
    			e1.printStackTrace();
    			resp.put("return_code", "FAIL");
    			resp.put("return_msg", "初始化微信支付参数失败!");
    			return resp;
    		} 
    	}
    	  			
        WXPay wxpay = new WXPay(config,SignType.MD5,false);  //上线环境 false,测试环境改为true

        Map<String, String> data = new HashMap<String, String>();
		data.put("out_trade_no", orderNum);
		
		try {
			resp = wxpay.orderQuery(data);
			System.out.println(resp);
		} catch (Exception e) {
			e.printStackTrace();
			resp.put("recode_code", "SUCCESS");
			resp.put("return_msg", "和微信支付通信失败!");
		}
		return resp;
	}
	
	
	
	
	
	
	
	
	
}
